package com.eatme.web.security.authentication.emailcode.provider;

import com.eatme.web.security.authentication.domain.entity.SecurityUser;
import com.eatme.web.security.authentication.emailcode.authentication.EmailCodeAuthenticationToken;
import com.eatme.web.security.authentication.emailcode.service.impl.EmailCodeSecurityUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

public class EmailCodeAuthenticationProvider implements AuthenticationProvider {

    private static final Logger LOG = LoggerFactory.getLogger(EmailCodeAuthenticationProvider.class);

    public final EmailCodeSecurityUserServiceImpl emailCodeUserDetailsServiceImpl;

    public EmailCodeAuthenticationProvider(EmailCodeSecurityUserServiceImpl emailCodeUserDetailsServiceImpl) {
        this.emailCodeUserDetailsServiceImpl = emailCodeUserDetailsServiceImpl;
    }


    /**
     * 认证
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (!supports(authentication.getClass())) {
            return null;
        }
        LOG.info("EmailCodeAuthentication authentication request: %s", authentication);
        EmailCodeAuthenticationToken token = (EmailCodeAuthenticationToken) authentication;

        // 从数据库查询 数据
        SecurityUser user = emailCodeUserDetailsServiceImpl.findByEmail((String) token.getPrincipal());
        LOG.info("Principal: {}",token.getPrincipal());
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        EmailCodeAuthenticationToken result = new EmailCodeAuthenticationToken(user,user.getAuthorities());
                /*
                Details 中包含了 ip地址、 sessionId 等等属性 也可以存储一些自己想要放进去的内容
                */
        result.setDetails(token.getDetails());
        LOG.info("Authentication: {}",user);
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return EmailCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}